package com.anyext.storage.config;

import java.util.UUID;

import org.springframework.beans.factory.BeanDefinitionStoreException;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.beans.factory.xml.AbstractBeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.util.StringUtils;
import org.w3c.dom.Element;

import com.anyext.storage.StorageContext;
import com.anyext.storage.impl.SessionImpl;

public class InitializeDefinitionParser extends AbstractBeanDefinitionParser {
	
	@Override
	protected String resolveId(Element element, AbstractBeanDefinition definition, ParserContext parserContext) throws BeanDefinitionStoreException {
		String id = super.resolveId(element, definition, parserContext);
		if(!StringUtils.hasText(id)) {
			id = UUID.randomUUID().toString();
		}
		return id;
	}

	@Override
	protected AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext) {
		RootBeanDefinition storageContext = new RootBeanDefinition();
		storageContext.setBeanClass(StorageContext.class);
		storageContext.setFactoryMethodName("getInstance");
		
		storageContext.getPropertyValues().add("session", new SessionImpl());
		
		return storageContext;
	}

}
